<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import type { DefResourceModel } from '#/api';
import type { RequestEnum } from '#/enums/httpEnum';

import { reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useFs } from '@fast-crud/fast-crud';
import { Alert, Card, Col, Row, Tag } from 'ant-design-vue';
import { split } from 'lodash-es';

import { BasicTitle } from '#/components/basic';
import { HTTP_TAG_MAP } from '#/enums/httpEnum';

import { createCrudOptions } from '../data/api-select-crud';

defineOptions({
  name: '资源接口选择',
  inheritAttrs: false,
});

const emit = defineEmits<Emits>();

interface Emits {
  (e: 'success', value: Recordable[]): void;
}

const formData = reactive<{
  selectedData: DefResourceModel.DefResourceApiVO[];
}>({
  selectedData: [],
});

const formRef = ref();

const { crudBinding } = useFs({ createCrudOptions, context: formData });

const [Modal, modalApi] = useVbenModal({
  async onOpenChange(isOpen) {
    if (isOpen) {
      formData.selectedData = modalApi.getData()?.selectedData;
    }
  },
  onConfirm() {
    try {
      modalApi.setState({ loading: true, confirmLoading: true });
      emit('success', formData.selectedData);
      modalApi.close();
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
});

function delSelectedDataByCard(obj: any) {
  const formDataRef = formRef.value.getFormData();

  const uris = formDataRef?.uri;
  if (uris) {
    const index = uris.findIndex((uri: any) => {
      const selected = split(uri, '#');
      return (
        selected[0] === obj.springApplicationName &&
        selected[2] === obj.uri &&
        selected[3] === obj.requestMethod
      );
    });
    if (index !== -1) {
      uris.splice(index, 1);
    }

    if (uris && uris.length > 0) {
      formRef.value.setFormData({ ...formDataRef, uri: uris });
    } else {
      formRef.value.setFormData({ ...formDataRef, uri: undefined });
    }
  }

  const index = formData.selectedData.findIndex(
    (selected: any) =>
      selected.springApplicationName === obj.springApplicationName &&
      selected.uri === obj.uri &&
      selected.requestMethod === obj.requestMethod,
  );

  if (index !== -1) {
    formData.selectedData.splice(index, 1);
  }
}

const getType = (requestMethod: RequestEnum) => {
  return HTTP_TAG_MAP.get(requestMethod) || 'default';
};

defineExpose(modalApi);
</script>

<template>
  <Modal title="资源接口选择" class="h-[80%] w-[80%]">
    <Row class="p-4">
      <Col :span="16">
        <div class="mx-4">
          <Alert type="info" class="mb-4" show-icon>
            <template #description>
              1. 配置此页面的资源接口时，建议后端启动微服务版 <br />
              2.
              若你坚持使用单体版，后端使用单体版本时：请注意“服务名”和“接口地址”一定要跟后端代码匹配
            </template>
          </Alert>
          <FsForm ref="formRef" v-bind="crudBinding.addForm" />
        </div>
      </Col>
      <Col :span="8">
        <div class="mb-2">
          <BasicTitle span line>
            已选接口 (
            <b class="text-red-500">{{ formData.selectedData.length }} </b>
            )：
          </BasicTitle>
        </div>

        <Card
          v-for="api in formData.selectedData"
          :key="api.springApplicationName + api.uri + api.requestMethod"
          class="mb-2"
          hoverable
          size="small"
          :title="api.name"
        >
          <template #extra>
            <a href="javascript:void(0);" @click="delSelectedDataByCard(api)">
              删除
            </a>
          </template>

          {{
            $t('devOperation.application.defResourceApi.springApplicationName')
          }}：
          {{ api.springApplicationName }}
          <br />
          {{ $t('devOperation.application.defResourceApi.controller') }}：{{
            api.controller
          }}

          <div
            class="cardDesc"
            :title="`(${api.requestMethod}) ${api.uri} (${api.controller})`"
          >
            <Tag :color="getType(api.requestMethod)">
              {{ api.requestMethod }}
            </Tag>
            {{ api.uri }}
          </div>
        </Card>
      </Col>
    </Row>
  </Modal>
</template>
